import {getCurrentInstance, inject, onMounted, reactive, ref, toRefs} from 'vue'
import {useRouter} from 'vue-router'
import {crmStore} from "../store";

export default function (screen) {
  const currentInstance = getCurrentInstance()
  const api = inject('api')
  const router = useRouter()
  const selects = ref([
    {
      label: '全部',
      value: 0
    },
    {
      label: '我负责的',
      value: 1
    },
    {
      label: '我下级负责的',
      value: 2
    },
    {
      label: '我部门负责的',
      value: 3
    },
  ])
  const orderTypes = ref([
    {
      label: '直发配送商',
      value: '1'
    },
    {
      label: '直发代理',
      value: '3'
    },
    {
      label: '直发终端',
      value: '2'
    },
    {
      label: '直发商销客户',
      value: '4'
    }
  ])
  const orderStatus = ref([
    {
      label: '审核未通过',
      value: '-1',
    },
    {
      label: '草稿',
      value: '0',
    },
    {
      label: '审核中',
      value: '1',
    },
    {
      label: '待发货',
      value: '2',
    },
    {
      label: '已发货（部分发货）',
      value: '3',
    },
    {
      label: '已发货',
      value: '4',
    },
    {
      label: '已取消',
      value: '5',
    },
    {
      label: '已收货',
      value: '6',
    },
  ])
  const userInfo = crmStore.getters['user/userInfo']
  const headOptions = crmStore.getters['company/getHeadOptions']

  var data = reactive({
    type: 'goods',
    tableData: [],
    formData: {
      page: 1,
      pageSize: 20,
      selectType: '',
      orderType: '',
      orderStatus: '',
      distributeName: '',
      teminalName: '',
      agentName: '',
      date: [],
      putOrderSort: '',
      createdSort: '',
      listType: '3',
      headId:'',
      sellerName:'',
    },
    total: 0,
    visible:false,
    heads:[],
    depHeads:[],
    lowerHeads:[],
  })

  const selectChange = () => {
    if (data.formData.selectType == 0) {
      data.heads = [...headOptions]
    }else if (data.formData.selectType == 2) {
      data.heads = [...data.lowerHeads]
    }else if (data.formData.selectType == 3) {
      data.heads = [...data.depHeads]
    }
    data.formData.headId = '';
    listSearch()
  }

  const addClick = () => {
    if (data.type === 'terminal') {
      router.push({ name: 'addOrder1', query: { type: 2 } })
    } else if (data.type === 'distributor') {
      router.push({ name: 'addOrder', query: { type: 1 } })
    } else if (data.type === 'agent') {
      router.push({ name: 'addAgentOrder', query: { type: 3} })
    } else if (data.type === 'business') {
      router.push({ name: 'addBusinessOrder', query: { type: 4} })
    }
  }

  const orderReset = () => {
    data.formData = {
      page: 1,
      pageSize: 20,
      selectType: '',
      orderType: '',
      orderStatus: '',
      putOrderSort: '',
      createdSort: '',
      listType: '3',
      headId:'',
      sellerName:'',
    }
    getList()
  }

  const rowClick = (row) => {
    if (data.type === 'goods') {
      router.push({ name: 'orderDetail', query: { id: row.order.id } })
    } else if (data.type === 'terminal') {
      router.push({ name: 'orderDetail3', query: { id: row.order.id } })
    } else if (data.type === 'distributor') {
      router.push({ name: 'orderDetail2', query: { id: row.order.id } })
    } else if (data.type === 'agent') {
      router.push({ name: 'agentOrderDetail', query: { id: row.order.id } })
    } else if (data.type === 'business') {
      router.push({ name: 'businessOrderDetail', query: { id: row.order.id } })
    }
  }

  const onEdit = (row) => {
    if (data.type == 'terminal') {
      router.push({ name: 'addOrder1', query: { id: row.order.id } })
    } else if (data.type === 'distributor') {
      router.push({ name: 'addOrder', query: { id: row.order.id } })
    } else if (data.type === 'agent') {
      router.push({ name: 'addAgentOrder', query: { id: row.order.id } })
    } else if (data.type === 'business') {
      router.push({ name: 'addBusinessOrder', query: { id: row.order.id } })
    }
  }

  const getList = () => {
    if (data.type == 'goods') {
      data.formData.listType = '3'
    } else if (data.type == 'terminal') {
      data.formData.listType = '2'
    } else if (data.type == 'distributor') {
      data.formData.listType = '1'
    } else if (data.type === 'agent') {
      data.formData.listType = '4'
    } else if (data.type === 'business') {
      data.formData.listType = '5'
    }
    let a = {...data.formData}
    a.headId = Number(a.headId)
    api.order.GET_ORDER_LIST(a).then(res => {
      if (!res.code && res.data) {
        data.tableData = res.data.list
        data.total = res.data.total
      }
    })
  }

  const createChange = (obj) => {
    if (obj.column) {
      if (obj.column.label == '创建时间') {
        if (obj.order) {
          if (obj.order == 'ascending') {
            data.formData.createdSort = 'asc'
          } else {
            data.formData.createdSort = 'desc'
          }
        } else {
          data.formData.createdSort = ''
        }
      } else {
        if (obj.order) {
          if (obj.order == 'ascending') {
            data.formData.putOrderSort = 'asc'
          } else {
            data.formData.putOrderSort = 'desc'
          }
        } else {
          data.formData.putOrderSort = ''
        }
      }
    } else {
      data.formData.putOrderSort = ''
      data.formData.createdSort = ''
    }

    listSearch()
  }

  const listSearch = () => {
    data.formData.page = 1
    getList()
  }

  const onCancel = (row) => {
    currentInstance.proxy
      .alertBox({
        message: '是否确认取消订单？',
        title: '取消订单',
      })
      .then(() => {
        api.order.ORDER_CANCEL(row.order.id).then(res => {
          if (!res.code) {
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '操作成功',
            })
            getList()
          } else {
            currentInstance.proxy.customMessage({ type: 'error', message: res.msg })
          }
        })
      })
      .catch((err) => {
        console.log(err)
      })
  }

  const onGoods = (row) => {
    let hint = '确认收货后将结束订单，是否要进行确认收货操作?'
    if (!row.order.ifAllDelivery) {
      hint = '该订单仍有部分产品未全部发货，确认订单后将结束订单，不能继续发货，是否要进行确认收货操作?'
    }
    currentInstance.proxy
      .alertBox({
        message: hint,
        title: '确认收货',
      })
      .then(() => {
        api.order.ORDER_CONFIRM_GOODS(row.order.id).then(res => {
          if (!res.code) {
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '操作成功',
            })
            getList()
          } else {
            currentInstance.proxy.customMessage({ type: 'error', message: res.msg })
          }
        })
      })
      .catch((err) => {
        console.log(err)
      })
  }

  const onDelete = (row) => {
    currentInstance.proxy
      .alertBox({
        message: '是否确认删除此订单？',
        title: '删除',
      })
      .then(() => {
        api.order.ORDER_DELETE(row.order.id).then((res) => {
          if (res.code) {
            currentInstance.proxy.customMessage({ type: 'error', message: res.msg })
          } else {
            currentInstance.proxy.customMessage({
              type: 'success',
              message: '删除成功',
            })
            getList()
          }
        })
      })
      .catch((err) => {
        console.log(err)
      })
  }

  // 获取下属职员列表
  const getUserList = () => {
    console.log(data.userInfo)
    var subdata = {
      userId: data.userInfo?.ID,
      types: 'lower',
    }
    api.common.USER_LIST(subdata).then((res) => {
      if (res.code === 0) {
        data.officeClerkOption = res.data || []
      }
    })
  }

  const getStatus = (row) => {
    let str = ''
    switch (row.order.orderStatus) {
      case '-1':
        str = '审核未通过'
        break
      case '0':
        str = '草稿'
        break
      case '1':
        str = '审核中'
        break
      case '2':
        str = '待发货'
        break
      case '3':
        str = '已发货（部分发货）'
        break
      case '4':
        str = '已发货'
        break
      case '5':
        str = '已取消'
        break
      case '6':
        str = '已收货'
        break
    }
    return str
  }

  const getDeptUser = () => {
    api.system.SYSDEPT_USER(userInfo.deptId).then((res) => {
      if (!res.code) {
        data.depHeads = res.data
      } else {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: res.msg,
        })
      }
    })
  }

  const getLowerUser = () => {
    let a = {
      userId: userInfo.ID,
      types: 'lower',
    }
    api.common.USER_LIST(a).then((res) => {
      if (res.code === 0) {
        data.lowerHeads = res.data || []
      } else {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: res.msg,
        })
      }
    })
  }

  onMounted(() => {
    data.type = screen
    data.heads = [...headOptions]
    getList()
    getDeptUser()
    getLowerUser()
  })

  return {
    ...toRefs(data),
    selects,
    orderTypes,
    orderStatus,

    getList,
    getStatus,
    onDelete,
    onGoods,
    onCancel,
    listSearch,
    createChange,
    rowClick,
    orderReset,
    addClick,
    onEdit,
    headOptions,
    selectChange,
  }
}

